package com.sensePlusVR.widget.dialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils.TruncateAt;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sensePlusVR.activity.follow.FollowDetailActivity;
import com.sensePlusVR.activity.follow.VideoPlayDialog;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.bean.ActorItem;
import com.sensePlusVR.bean.CollectionItem;
import com.sensePlusVR.bean.CommendItem;
import com.sensePlusVR.bean.GameItem;
import com.sensePlusVR.db.ImageLibrary;
import com.sensePlusVR.db.ImageLibrary.Callback;
import com.sensePlusVR.main.MainActivity;
import com.sensePlusVR.main.R;
import com.sensePlusVR.manager.ActorManager;
import com.sensePlusVR.manager.CollectionFollowManager;
import com.sensePlusVR.manager.CommendItemManager;
import com.sensePlusVR.manager.DataCenter;
import com.sensePlusVR.manager.EventListener;
import com.sensePlusVR.setting.bluetooth.BlueScannerActivity;
import com.sensePlusVR.utils.BitmapUtil;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.DateTimeUtil;
import com.sensePlusVR.utils.DensityUtil;
import com.sensePlusVR.utils.DialogUtils;
import com.sensePlusVR.utils.DownloadBatchUrl;
import com.sensePlusVR.utils.DownloadTask;
import com.sensePlusVR.utils.FileConvertUtil;
import com.sensePlusVR.utils.GameController;
import com.sensePlusVR.utils.GameDownload;
import com.sensePlusVR.utils.GameUpgradeUtils;
import com.sensePlusVR.utils.MyDialogUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MyPageJump;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.MyToast;
import com.sensePlusVR.utils.NetworkUtils;
import com.sensePlusVR.widget.CircleDLProgressView;
import com.sensePlusVR.widget.MarqueeHorTextView;
import com.senseplusvr.sdk.videoview.GLView;
import com.senseplusvr.sdk.videoview.SvrVideoView;
import com.senseplusvr.sdk.videoview.SvrVideoView.OnSvrEventListener;
import com.senseplusvr.sdk.videoview.SvrVideoView.SvrViewType;
import com.senseplusvr.sdk.videoview.SvrVideoView.playerEvent;

import java.util.ArrayList;

@SuppressLint({ "RtlHardcoded", "InflateParams" })
@SuppressWarnings("unused")
public class VideoDetailDialog extends BaseDialog implements
		View.OnClickListener, DownloadBatchUrl.DownloadCallBack {

	private static final String TAG = VideoDetailDialog.class.getSimpleName();
	
	public static final int DOWNLOAD_STATE_TO_START = 10;//需要下载Icon
	public static final int DOWNLOAD_STATE_TO_DOING = 11;//正在下载Icon
	public static final int DOWNLOAD_STATE_TO_END = 12;//下载完成Icon
	
	private Context context;
	private GameItem gameItem;
	private CommendItem commendItem;
	private boolean isShowFollowDetail;

	private LinearLayout video_detail_linear1;
	private LinearLayout video_detail_linear2;
	private ImageView detail_actor_iv;
	private TextView detail_actor_name_tv;

	private LinearLayout detail_honey_linear;
	private ImageView detail_honey_iv;

	private SvrVideoView svrVideoView;
	private RelativeLayout svrVideoView_relative;
	private RelativeLayout svr_relative;
	private CircleDLProgressView circleDLProgressView;
	private MarqueeHorTextView detail_game_director_tv;

	private RelativeLayout svr_cover_relative;
	private ImageView game_new_iv;
	private ImageView game_vr_iv;

	private LinearLayout detail_zambia_up_linear;
	private ImageView detail_zambia_up_iv;
	private TextView detail_zambia_up_tv;
	private TextView detail_game_size_tv;


//	private LinearLayout detail_download_linear;
//	private ImageView detail_download_iv;

	private LinearLayout detail_colletion_linear;
	private ImageView detail_colletion_iv;
	
	private RelativeLayout detail_download_or_play_relative;
	private TextView detail_download_or_play_tv;
	private ImageView detail_downloading_points_iv;

//	private TextView detail_vr_play;
//	private TextView detail_play;
	
	//guide tip
	private boolean isShowedGuide;
	private ViewGroup download_guide;
	private ViewGroup favorate_guide;
	
	private RelativeLayout guide_download_relative;
	private ImageView guide_favorate_iv;
	private RelativeLayout guide_favorite_tag_relative;

	private VRApplication vrApplication;
	private AnimationDrawable animationDrawable;//下载图标动画

	private ActorItem actorItem;
	private int followed;
	private int userAction;
	private DataCenter dataCenter;
	private final String KEY = this.getClass().getSimpleName();
	
	private Handler handler;
	private static final int ANIMATION_DELAY = 2000; 
	
	private boolean isDisPlayNew = false;
	private boolean isDisPlayVR = false;
	
	EventListener listener = new EventListener() {

		@Override
		public void Notify(int event, Object data, Object Params) {
			if (Params == null || data == null)
				return;
			if (event == CommendItemManager.EventCommendGot) {
				CommendItem citem = (CommendItem) data;
				if (citem == null)return;
				if (citem.getUp() != commendItem.getUp()
						|| citem.getUserAction() != commendItem.getUserAction()) {
					commendItem.setUp(citem.getUp());
					commendItem.setUserAction(citem.getUserAction());
					updateCommend();
				}
			}
		}

	};

	EventListener CFlistener = new EventListener() {

		@Override
		public void Notify(int event, Object data, Object Params) {
			if (Params == null || data == null)
				return;
			MyLog.e(TAG, "event=" + event);
			if (event >= CollectionFollowManager.EventErrorBase) {
				int resId = (Integer) data;

				event -= CollectionFollowManager.EventErrorBase;
				if (event == CollectionFollowManager.EventFollowAdded) {
					if (resId != actorItem.getId())
						return;
					updateFollowed(0);// add error, set follow to 0
				} else if (event == CollectionFollowManager.EventFollowDeled) {
					updateFollowed(1);
					if (resId != actorItem.getId())
						return;
				}
			}
		}

	};

	EventListener actorListener = new EventListener() {

		@Override
		public void Notify(int event, Object data, Object Params) {
			if (event == ActorManager.EventActorAllGot) {
				if (gameItem == null)
					return;
				actorItem = dataCenter.getActorByName(gameItem.getActors()); // gameItem.getActoritem();
				if (actorItem != null) {
					MyLog.d(TAG, "actorListener actorItem : " + actorItem.toString());
					followed = actorItem.getFollowed();// 0 表示未关注 1表示已经关注
					updateActor();
				}else{
					MyLog.d(TAG, "actorListener actorItem == null");
				}
			}
		}

	};


	@Override
	public void progress(Object param, final int progress, int downloadState) {
		GameItem item = (GameItem) param;
		if (item.getId() == gameItem.getId()) {
			if (downloadState==DownloadTask.DownloadSuccess) {
				if (progress == 100) {
					showToast(0);
				} else if(downloadState==DownloadTask.DownloadFailed){
					showToast(1);
				}
			}
		}
	}
	
	private void showToast(int event) {
		if (event == 0) {
			((BaseActivity) context).runOnUiThread(new Runnable() {
				@Override
				public void run() {
					MyLog.d(TAG, "Download complete");
					//detail_download_iv.setImageResource(R.drawable.video_detail_downed);
					downloadedPlayUI();
				}
			});
		}
		if (event == 1) {
			((BaseActivity) context).runOnUiThread(new Runnable() {
				@Override
				public void run() {
					MyToast.showMessage(context, context.getString(R.string.download_failed_try_again));
					//detail_download_iv.setImageResource(R.drawable.video_detail_selector);
					toDownloadPlayUI();
				}
			});
		}
	}

	public VideoDetailDialog(Context context, GameItem gameItem,
			CommendItem commendItem, int theme, boolean isShowFollowDetail) {
		super(context, theme);
		this.context = context;
		this.gameItem = gameItem;
		this.commendItem = commendItem;
		this.isShowFollowDetail = isShowFollowDetail;
		if (gameItem != null)
			MyLog.d(TAG, "gameItem :" + gameItem.toString());
		if (commendItem != null)
			MyLog.d(TAG, "commendItem : " + commendItem.toString());
		initData();
	}

	private void addDelCommentListener(boolean add) {
		if (add) {
			dataCenter.addCommendEventListener(listener, gameItem, KEY
					+ gameItem.getId());
			dataCenter.addActorEventListener(actorListener, this, KEY);
			dataCenter.addFCEventListener(CFlistener, this, KEY);
		} else {
			dataCenter.delCommendEventListener(KEY + gameItem.getId());
			dataCenter.delActorEventListener(KEY);
			dataCenter.delFCEventListener(KEY);
		}
	}

	private void initData() {
		handler = new Handler();
		dataCenter = DataCenter.getInstans();
		addDelCommentListener(true);

		vrApplication = (VRApplication) ((BaseActivity) context)
				.getApplication();

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_video_detail);
		initViews();
	}

	@Override
	public void dismiss() {
		super.dismiss();
		MyLog.d(TAG, "dismiss");
		if(animationDrawable != null &&animationDrawable.isRunning()){
			animationDrawable.stop();
		}
		boolean isShowingVideo = svrVideoView.isShowingVideo();
		if (isShowingVideo)svrVideoView.stopVideo();
		addDelCommentListener(false);
		
	}

	private void initViews() {
		video_detail_linear1 = (LinearLayout) findViewById(R.id.video_detail_linear1);
		video_detail_linear2 = (LinearLayout) findViewById(R.id.video_detail_linear2);
		detail_actor_iv = (ImageView) findViewById(R.id.detail_actor_iv);
		detail_actor_name_tv = (TextView) findViewById(R.id.detail_actor_name_tv);
		detail_honey_linear = (LinearLayout) findViewById(R.id.detail_honey_linear);
		detail_honey_iv = (ImageView) findViewById(R.id.detail_honey_iv);
		detail_game_director_tv = (MarqueeHorTextView) findViewById(R.id.detail_game_director_tv);
		svrVideoView_relative = (RelativeLayout) findViewById(R.id.svrVideoView_relative);

		detail_zambia_up_linear = (LinearLayout) findViewById(R.id.detail_zambia_up_linear);
		detail_zambia_up_iv = (ImageView) findViewById(R.id.detail_zambia_up_iv);
		detail_zambia_up_tv = (TextView) findViewById(R.id.detail_zambia_up_tv);
		detail_game_size_tv = (TextView) findViewById(R.id.detail_game_size_tv);

//		detail_download_linear = (LinearLayout) findViewById(R.id.detail_download_linear);
//		detail_download_iv = (ImageView) findViewById(R.id.detail_download_iv);

		detail_colletion_linear = (LinearLayout) findViewById(R.id.detail_colletion_linear);
		detail_colletion_iv = (ImageView) findViewById(R.id.detail_colletion_iv);

		
		detail_download_or_play_relative = (RelativeLayout) findViewById(R.id.detail_download_or_play_relative);
		detail_download_or_play_tv = (TextView) findViewById(R.id.detail_download_or_play_tv);
		detail_downloading_points_iv = (ImageView) findViewById(R.id.detail_downloading_points_iv);
//		detail_vr_play = (TextView) findViewById(R.id.detail_vr_play);
//		detail_play = (TextView) findViewById(R.id.detail_play);

		// 动态添加svrVideoView到xml中,因为静态在dialog中会报Caused by:
		// java.lang.RuntimeException: Context must be an instance of activity
		svrVideoView = new SvrVideoView(context);
		svrVideoView.setLayoutParams(new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
		svrVideoView.setVisibility(View.INVISIBLE);

		svr_relative = new RelativeLayout(context);
		svr_relative.setLayoutParams(new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
		svr_relative.setBackgroundColor(context.getResources().getColor(
				R.color.pro_download_bg));
		svr_relative.setGravity(Gravity.CENTER);
		svr_relative.setVisibility(View.INVISIBLE);

		circleDLProgressView = new CircleDLProgressView(context);
		// 设置环形进度直径.(dp转化为px)
		int proCalibre = DensityUtil.dip2px(context, 100);
		circleDLProgressView.setLayoutParams(new RelativeLayout.LayoutParams(proCalibre,
				proCalibre));
		// 设置进度最大参数
		circleDLProgressView.setMaxCount(100);
		circleDLProgressView.setScoreSpSize(20);
		circleDLProgressView.setCircleStrokeWithSp(1.5f);
		circleDLProgressView.setBackCircleColor(context.getResources()
				.getColor(R.color.download_pro_bg));

		svr_relative.addView(circleDLProgressView);
		// 设置svrvideoVideo默认图片自定义view
		svr_cover_relative = new RelativeLayout(context);
		svr_cover_relative.setLayoutParams(new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
		svr_cover_relative.setBackgroundColor(context.getResources().getColor(
				R.color.setting_account_bg));
		svr_cover_relative.setGravity(Gravity.CENTER);
		ImageView svr_cover_img = new ImageView(context);
		svr_cover_img.setLayoutParams(new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		svr_cover_img.setScaleType(ScaleType.CENTER_INSIDE);
		svr_cover_img.setImageDrawable(ContextCompat.getDrawable(context,
				R.drawable.loadng_icon));

		svr_cover_relative.addView(svr_cover_img);
		
		game_new_iv = new ImageView(context);
		RelativeLayout.LayoutParams lp_new = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		game_new_iv.setLayoutParams(lp_new);
		game_new_iv.setPadding(0, DensityUtil.dip2px(context, 12), 0, 0);
		game_new_iv.setScaleType(ScaleType.CENTER_INSIDE);
		game_new_iv.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.video_new_tag_big));
		game_new_iv.setVisibility(View.INVISIBLE);
		
		game_vr_iv = new ImageView(context);
		RelativeLayout.LayoutParams lp_vr = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		lp_vr.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		game_vr_iv.setLayoutParams(lp_vr);
		game_vr_iv.setPadding(0, 0,DensityUtil.dip2px(context, 5), 0);
		game_vr_iv.setScaleType(ScaleType.CENTER_INSIDE);
		game_vr_iv.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.vronly_tag_big));
		game_vr_iv.setVisibility(View.INVISIBLE);
		

		svrVideoView_relative.addView(svr_cover_relative);
		svrVideoView_relative.addView(svrVideoView);
		svrVideoView_relative.addView(svr_relative);
		svrVideoView_relative.addView(game_new_iv);
		svrVideoView_relative.addView(game_vr_iv);

		video_detail_linear1.setOnClickListener(this);
		video_detail_linear2.setOnClickListener(this);
		detail_honey_linear.setOnClickListener(this);
		detail_actor_iv.setOnClickListener(this);
		detail_game_director_tv.setOnClickListener(this);
		detail_zambia_up_linear.setOnClickListener(this);
		detail_colletion_iv.setOnClickListener(this);
		detail_download_or_play_relative.setOnClickListener(this);
		svrVideoView.setOnSvrEventListener(new MyOnSvrEventListener());

		setClickble(true);
		
		GameDownload.setGameProgressNotify(this, KEY);

		//设置初始数据
		addDataToItem(gameItem, commendItem);
		
		checkGuide();
		
	}

	/**
	 * @param isBottomClick true:可点击，false:不可点击
	 * 动态设置最底层View的点击事件是否可点击
	 */
	private void setClickble(boolean isBottomClick){
		video_detail_linear1.setClickable(isBottomClick);
		video_detail_linear2.setClickable(isBottomClick);
		detail_honey_linear.setClickable(isBottomClick);
		detail_actor_iv.setClickable(isBottomClick);
		detail_game_director_tv.setClickable(isBottomClick);
		detail_zambia_up_linear.setClickable(isBottomClick);
		detail_colletion_iv.setClickable(isBottomClick);
		detail_download_or_play_relative.setClickable(isBottomClick);
		//setOnSvrEventListener做特殊处理
		if(isBottomClick){
			svrVideoView.setOnSvrEventListener(new MyOnSvrEventListener());
		}else{
			svrVideoView.setOnSvrEventListener(null);	
		}
		
	}
	
	/**
	 * 检测显示Guide
	 */
	private void checkGuide() {
		isShowedGuide = MySharedPreferences.getBoolean2(context, MySharedPreferences.NAME_NOT_CLEAR, Constant.SP_GUIDE_VIDEODETALI_DIALOG);
		if(!isShowedGuide && isShowFollowDetail){
			setClickble(false);
			favorate_guide = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.guide_view_favorate, null);
			download_guide = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.guide_view_download, null);
			
			addContentView(download_guide, new LayoutParams(-1, -1));
			
			MySharedPreferences.save2(context, MySharedPreferences.NAME_NOT_CLEAR, Constant.SP_GUIDE_VIDEODETALI_DIALOG,true);
		}
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		MyLog.d(TAG, "hasFocus : " + hasFocus);
		if(!isShowedGuide && hasFocus && isShowFollowDetail){
			addDownloadView();
		}
	}
	
	private void addDownloadView() {
		//下载按钮
		final int[] locationDownload = new int[2];
		detail_download_or_play_relative.getLocationOnScreen(locationDownload);
		
		guide_download_relative = (RelativeLayout) download_guide.findViewById(R.id.guide_download_relative);
		RelativeLayout.LayoutParams lpDownload = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);

		lpDownload.leftMargin = locationDownload[0];
		lpDownload.rightMargin = locationDownload[0];
		lpDownload.topMargin = locationDownload[1] - DensityUtil.getStatusBarHeight(context);
		guide_download_relative.setLayoutParams(lpDownload);
		
		guide_download_relative.setOnClickListener(this);
		
		//收藏Tag
		LinearLayout main_linear_myGame = (LinearLayout) ((MainActivity)context).findViewById(R.id.main_linear_myGame);
		final int[] locationFavoriteTag = new int[2];
		main_linear_myGame.getLocationOnScreen(locationFavoriteTag);
		guide_favorite_tag_relative = (RelativeLayout) download_guide.findViewById(R.id.guide_favorite_tag_relative);
		RelativeLayout.LayoutParams lpFavoriteTag = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		lpFavoriteTag.width = DensityUtil.getScreenWidth(context)/4;
		lpFavoriteTag.height = guide_favorite_tag_relative.getHeight();
		lpFavoriteTag.leftMargin = locationFavoriteTag[0];
		lpFavoriteTag.topMargin = locationFavoriteTag[1] - DensityUtil.getStatusBarHeight(context);
		guide_favorite_tag_relative.setLayoutParams(lpFavoriteTag);
	}
	
	private void addFavorateView(){
		addContentView(favorate_guide, new LayoutParams(-1, -1));
		final int[] locationFavorite = new int[2];
		detail_colletion_iv.getLocationOnScreen(locationFavorite);
		
		guide_favorate_iv = (ImageView) favorate_guide.findViewById(R.id.guide_favorate_iv);
		RelativeLayout.LayoutParams lpFavorite = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);

		lpFavorite.leftMargin = locationFavorite[0];
		lpFavorite.topMargin = locationFavorite[1] - DensityUtil.getStatusBarHeight(context);
		guide_favorate_iv.setLayoutParams(lpFavorite);
		
		guide_favorate_iv.setOnClickListener(this);
	}
	
	
	

	class MyOnSvrEventListener implements OnSvrEventListener {

		@Override
		public void onControlViewClick() {
			MyLog.d(TAG, "onControlViewClick...");
			toPlayVideo();
		}

		@Override
		public void onPlayerEvent(playerEvent event) {
			switch (event) {
			case View_playing:
				break;
			case View_stop:
				notPlayingUI();
				break;
			case View_end:
				notPlayingUI();
				break;
			case View_showPoster:
				notPlayingUI();
				break;
			case View_showvideo:
				break;
			}
		
		}

	}
	

	private void playingUI() {
		game_new_iv.setVisibility(View.INVISIBLE);
		game_vr_iv.setVisibility(View.INVISIBLE);
	}
	

	private void notPlayingUI() {
		if(isDisPlayNew){
			game_new_iv.setVisibility(View.VISIBLE);
		}else{
			game_new_iv.setVisibility(View.INVISIBLE);
		}
		
		if(isDisPlayVR){
			game_vr_iv.setVisibility(View.VISIBLE);
		}else{
			game_vr_iv.setVisibility(View.INVISIBLE);
		}
	}

	void updateCommend() {
		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				detail_zambia_up_tv.setText(String.valueOf(commendItem.getUp()));
			}
		});
	}

	void updateFollowed(final int actorFollowed) {
		MyLog.e(TAG, "update follow = " + actorFollowed);
		followed = actorFollowed;
		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (actorItem == null) {
					return;
				}
				actorItem.setFollowed(actorFollowed);
				cornerFollowBackbround(actorFollowed);
			}
		});
	}

	private void cornerFollowBackbround(int followed) {
		MyLog.d(TAG, "cornerFollowBackbround followed : " + followed);
		if (followed == 0) {
			detail_honey_iv.setImageResource(R.drawable.video_detail_addfollow_selector);
		} else if (followed == 1) {
			detail_honey_iv.setImageResource(R.drawable.video_detail_minusfollow_selector);
		}
	}

	void updateCollectioned(final int gameCollectioned) {
		MyLog.e(TAG, "update gameCollectioned = " + gameCollectioned);
		gameItem.setColloctoned(gameCollectioned);
		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (gameCollectioned == 0) {
					detail_colletion_iv
							.setImageResource(R.drawable.collect_add_selector);
				} else if (gameCollectioned == 1) {
					detail_colletion_iv
							.setImageResource(R.drawable.collected_selector);
				}
			}
		});

	}

	void updateActor() {

		((BaseActivity) context).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				ActorItem actorItem = null;
				String actorImageUrl = "";
				String actorName = "";
				int actorFollowed = 0;

				if (gameItem != null) {
					actorItem = ActorItem.getActorByName(gameItem.getActors());// gameItem.getActoritem();
					if (actorItem != null) {
						actorImageUrl = actorItem.getImgurl();// actor 头像
						actorName = actorItem.getName();// actor name
						actorFollowed = actorItem.getFollowed();// actor 是否被关注过
					}
				}

				cornerFollowBackbround(actorFollowed);

				MyLog.d(TAG, "actorImageUrl :" + actorImageUrl);
				ImageLibrary.getInstance().getImageBitmap(context,
						actorImageUrl, new Callback() {
							@Override
							public void onImageDownloaded(Bitmap bitmap) {
								MyLog.d(TAG, "bitmap : " + bitmap);
								if (bitmap != null) {
									detail_actor_iv.setImageBitmap(bitmap);
								}
							}
						});
				detail_actor_name_tv.setText(actorName);

			}
		});
	}


	/**
	 * 往Item中添加显示内容
	 *
	 */
	private void addDataToItem(final GameItem gameItem, CommendItem commendItem) {

		if (gameItem == null)
			return;
		// 收藏 or 下载
		CollectionItem clcItem = CollectionItem.query(gameItem.getId());

		boolean isFavorited = clcItem != null;

		int needToLoadingIcon = downloadStateIcon(clcItem);

		if (isFavorited) {

			detail_colletion_iv.setImageResource(R.drawable.collected_selector);

		} else {

			detail_colletion_iv
					.setImageResource(R.drawable.collect_add_selector);
		}

		if (needToLoadingIcon == DOWNLOAD_STATE_TO_START) {
			toDownloadPlayUI();
		} else if(needToLoadingIcon == DOWNLOAD_STATE_TO_DOING){
			downloadingPlayUI();
		}else if(needToLoadingIcon == DOWNLOAD_STATE_TO_END){
			downloadedPlayUI();
			
		}

		// 踩赞及踩赞个数
		String uped = "";
		if (commendItem != null) {
			uped = String.valueOf(commendItem.getUp());
			userAction = commendItem.getUserAction();
		}

		if (userAction == 0) {
			detail_zambia_up_iv
					.setImageResource(R.drawable.favour_pop_selector);
		} else if (userAction == 1) {
			detail_zambia_up_iv.setImageResource(R.drawable.favour_pop);
		}
		
		detail_zambia_up_tv.setText(uped);
		detail_game_director_tv.setText(gameItem.getTitle());
		detail_game_size_tv.setText(FileConvertUtil.getMbGbFileSize(gameItem.getSize()));

		svrVideoView.setVisibility(View.INVISIBLE);
		svr_cover_relative.setVisibility(View.VISIBLE);
		svrVideoView.setVideoPara(gameItem.getTitle(),gameItem.getVideourl(),
				GLView.VideoType.video_2d,
				BitmapUtil.getBitmapFromResID(context, R.drawable.loadng_icon));
		svrVideoView.setViewType(SvrViewType.View_dialog);
		ImageLibrary.getInstance().getImageBitmap(context,
				gameItem.getImgurl(), new Callback() {

					@Override
					public void onImageDownloaded(Bitmap bitmap) {
						MyLog.d(TAG, "bitmap : " + bitmap);
						if (bitmap != null) {
							svrVideoView.setVisibility(View.VISIBLE);
							svr_cover_relative.setVisibility(View.INVISIBLE);
							svrVideoView.setVideoPara(gameItem.getTitle(),gameItem.getVideourl(),
									GLView.VideoType.video_2d, bitmap);
						}
					}
				});

		// 演员
		actorItem = dataCenter.getActorByName(gameItem.getActors());// gameItem.getActoritem();
		if (actorItem == null){
			MyLog.d(TAG,"actorItem == null ");
			return;
		}
		MyLog.d(TAG,"actorItem : " + actorItem.toString());	
		// 演员头像
		ImageLibrary.getInstance().getImageBitmap(context,
				actorItem.getImgurl(), new Callback() {
					@Override
					public void onImageDownloaded(Bitmap bitmap) {
						MyLog.d(TAG, "bitmap : " + bitmap);
						if (bitmap != null)
							detail_actor_iv.setImageBitmap(bitmap);
					}
				});
		// 演员名称
		detail_actor_name_tv.setText(actorItem.getName());
		// 演员是否被关注(获取初始关注状态方便判断关注还是取消关注)
		followed = actorItem.getFollowed();
		cornerFollowBackbround(followed);
		
		isDisPlayNew(gameItem);

	}

	private void isDisPlayNew(GameItem gameItem) {
		String gameCreateTime = gameItem.getCreatetime();
		gameCreateTime = DateTimeUtil.removeZoneTime(gameCreateTime);
		if(DateTimeUtil.isLessPreviousMonth(gameCreateTime)){
			game_new_iv.setVisibility(View.VISIBLE);
			isDisPlayNew = true;
		}else{
			game_new_iv.setVisibility(View.INVISIBLE);
			isDisPlayNew = false;
		}
		
		boolean isVROnly = GameItem.isVROnly(gameItem);
		if(isVROnly){
			game_vr_iv.setVisibility(View.VISIBLE);
			isDisPlayVR = true;
		}else{
			game_vr_iv.setVisibility(View.INVISIBLE);
			isDisPlayVR = false;
		}
	}
	
	private void downloadedPlayUI(){
		detail_download_or_play_relative.setBackgroundResource(R.drawable.play_btn_bg_p);
		detail_downloading_points_iv.setVisibility(View.INVISIBLE);
		boolean isVrOnly = GameItem.isVROnly(gameItem);
		boolean is2DOnly = GameItem.is2DOnly(gameItem);
		if(isVrOnly){
			detail_download_or_play_tv.setText(R.string.vr_play_only);
		}else if(is2DOnly){
			detail_download_or_play_tv.setText(R.string.nomo_play_only);
		}else{
			detail_download_or_play_tv.setText(R.string.play);
		}
		detail_download_or_play_tv.setTextColor(ContextCompat.getColor(context, R.color.app_text_color_white));
	}
	
	private void toDownloadPlayUI(){
		detail_download_or_play_relative.setBackgroundResource(R.drawable.play_btn_bg_selector);
		detail_downloading_points_iv.setVisibility(View.INVISIBLE);
		detail_download_or_play_tv.setText(R.string.download);
		detail_download_or_play_tv.setTextColor(ContextCompat.getColor(context, R.color.app_text_color_white));
	}
	
	private void downloadingPlayUI(){
		detail_download_or_play_relative.setBackgroundResource(R.drawable.play_btn_bg_selector);
		detail_download_or_play_tv.setText(R.string.download_game_isDownloading);
		detail_download_or_play_tv.setTextColor(ContextCompat.getColor(context, R.color.app_text_color_gray5));
		detail_downloading_points_iv.setVisibility(View.VISIBLE);
		detail_downloading_points_iv.setImageResource(R.drawable.loading_points_animlist);
		animationDrawable = (AnimationDrawable) detail_downloading_points_iv.getDrawable();
		if(!animationDrawable.isRunning()){
			animationDrawable.start(); 
		}
	}

	private void gameDownload(GameItem gameItem) {
		GameDownload.downloadGame(gameItem);
	}
	

	private void gameStart(int gameMode) {
		
		MySharedPreferences.save(context, Constant.SP_BLUE_IS_FROM_SETTING,
				false);
	
		boolean isRealGame = GameItem.isRealGame(gameItem);
		
//		if (!Constant.nativeBundleSwitch) {
			
			CollectionItem clcItem = CollectionItem.query(gameItem.getId());
			
			if(clcItem!=null){
				
				int downloadState = clcItem.getDownloadState();
				
				if(downloadState<=CollectionItem.DownloadPause){
					
//					MyToast.showMessage(
//							context,
//							context.getResources().getString(
//									R.string.download_game_tip));
					
					return;
					
				}else if(clcItem.getDownloadState()==CollectionItem.DownloadDoing){
					
					MyToast.showMessage(
							context,
							context.getResources().getString(
									R.string.isDownloading));
					
					return;
				}else if(clcItem.getDownloadState()==CollectionItem.DownloadFinished){
					//下载完成如果需要更新游戏则执行
					boolean isUpgrade = GameUpgradeUtils.isToUpgradeGameItem(gameItem);
					MyLog.d(TAG, "isRealGame : " + isRealGame + " isUpgrade : " + isUpgrade);
					MyLog.d(TAG, "gameItem : " + gameItem);
					
					if(isUpgrade && isRealGame){
						GameUpgradeUtils gameupdate = GameUpgradeUtils.getInstance();
						gameupdate.updateConfigDownloaded(gameItem, context);
						
						dismiss();
						
						return;
					}
				}
				
				
				
				
			}else{
				
//				MyToast.showMessage(
//						context,
//						context.getResources().getString(
//								R.string.download_game_tip));
				
				return;
				
			}
			
			

//		}
		boolean isConnectedVR = vrApplication.isBTConnected();
		if (isConnectedVR) {
			boolean isFromSetting = MySharedPreferences.getBoolean(context,
					Constant.SP_BLUE_IS_FROM_SETTING);
			if (!isFromSetting) {
//				if (Constant.nativeBundleSwitch) {
//
//					if (isRealGame) {
//
//						JumpGameTest.jumpRealActivity(context,
//								gameMode == Constant.GAME_MODE_VR);
//
//					} else {
//
//						JumpGameTest.jumpVRActivity(context,
//								gameMode == Constant.GAME_MODE_VR);
//					}
//
//				} else {

					GameController.GameStartOne(context, gameMode, isRealGame,
							GameDownload.getGameConfig(gameItem),gameItem);
//				}

			}
		} else {
			vrApplication.toBTDisconnect();
//			if (!Constant.nativeBundleSwitch) {
//
//				// 没有连接上则先set数据到GameController中，然后在bluescan中在GameStartOne不用传数据了.
//				List<String> glist = new ArrayList<String>();
//				glist.add(GameDownload.getGameConfig(gameItem));
//				GameController.GameSetList(gameMode, isRealGame, glist);
//
//			} else {

				GameController.GameSetList(gameMode, isRealGame, null,gameItem);

//			}

			MyPageJump.pageJump(context, BlueScannerActivity.class);
		}
	}
	
	/**
	 * 三种状态：没下载，下载中，下载完成显示不同Icon
	 * @param clcItem
	 * @return
	 */
	private int downloadStateIcon(CollectionItem clcItem){
		
	if(clcItem==null){
			
			return DOWNLOAD_STATE_TO_START;
		}
		
		int state = clcItem.getDownloadState();
		
		if(state==CollectionItem.DownloadDoing){
			
			return DOWNLOAD_STATE_TO_DOING;
			
		}else if(state==CollectionItem.DownloadPause || state==CollectionItem.DownloadNone||state==CollectionItem.DownloadError){
		
			return DOWNLOAD_STATE_TO_START;
			
		}else if(state == CollectionItem.DownloadFinished){
			
			return DOWNLOAD_STATE_TO_END;
		}
		
		return DOWNLOAD_STATE_TO_START;
		
	}

	@Override
	public void setOnDismissListener(OnDismissListener listener) {
		super.setOnDismissListener(listener);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.root_video_detail:
		case R.id.video_detail_linear1:
		case R.id.video_detail_linear2:
			MyLog.d(TAG, "top bootem dismiss.....");
			if (isShowing()) {
				MyLog.e(TAG, "top bootem dismiss call");
				GameDownload.setGameProgressNotify(null, KEY);
				if (isShowing())
					dismiss();
			}
			break;
		// 点击头像进入进入女优详情
		case R.id.detail_actor_iv:
			MyLog.d(TAG, "detail_actor_iv");
			if (isShowFollowDetail) {
				if(actorItem!=null){
					MyLog.d(TAG, "actorItem : " + actorItem.toString());
				}else{
					MyLog.d(TAG, "actorItem == null");
				}
				MyPageJump.pageJumpAddObject(context,
						FollowDetailActivity.class,actorItem, -1);
				if (isShowing())
					dismiss();
			}
			break;
		// 关注
		case R.id.detail_honey_linear:
			MyLog.d(TAG, "detail_honey_linear");
			if (actorItem == null){
				MyLog.d(TAG, "action item is null");
				break;
			}
			// 关注取消关注在第一次从服务器获取数据，再次点击时则本地改变状态，服务器也改变了，只是没有获取列表信息，下次获取列表信息则为最新数据.
			if (followed == 0) {
				uploadFollow();
				detail_honey_iv.setImageResource(R.drawable.video_detail_minusfollow_selector);
				MyToast.showMessage(context, R.string.follow_added);
				followed = 1;
			} else if (followed == 1) {
				String message = context.getString(R.string.follow_delete);
				DialogUtils.showConfirmDialogConfirmCancel(context, null,
						message, new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								cancelFollow();
								detail_honey_iv.setImageResource(R.drawable.video_detail_addfollow_selector);
								followed = 0;
								dialog.dismiss();
							}
						}, new OnClickListener() {// 取消的退出功能
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								followed = 1;
								dialog.dismiss();
							}
						});
			}
			if (actorItem != null)
				actorItem.setFollowed(followed);
			if (gameItem != null)
				gameItem.setActoritem(actorItem);
			break;
			//当点击director时则走马灯显示
		case R.id.detail_game_director_tv:
			detail_game_director_tv.setEllipsize(TruncateAt.MARQUEE);
			break;
		// 点赞
		case R.id.detail_zambia_up_linear:
			MyLog.d(TAG, "detail_zambia_up_linear");
			if (userAction == 0) {
				uploadCommend();
				detail_zambia_up_iv.setImageResource(R.drawable.favour_pop);
				userAction = 1;
				if (commendItem != null) {
					commendItem.setUserAction(userAction);
					int uped = commendItem.getUp() + 1;
					commendItem.setUp(uped);
					detail_zambia_up_tv.setText(String.valueOf(uped));
				}
			} else if (userAction == 1) {
				MyToast.showMessage(
						context,
						context.getResources().getString(
								R.string.commended_already));
			}
			break;
		// 收藏
//		case R.id.detail_colletion_linear:
		case R.id.detail_colletion_iv:{

			final CollectionItem clcItem = CollectionItem.query(gameItem.getId());
			
			if(clcItem==null){//需要搜藏
				
				MyLog.d(TAG, "current time 111 : " + System.currentTimeMillis());
				
				detail_colletion_iv.setImageResource(R.drawable.collected_selector);
				
				MyLog.d(TAG, "current time 222 : " + System.currentTimeMillis());
				
				MyToast.showMessage(context, R.string.collection_added);
				
				MyLog.d(TAG, "current time 333 : " + System.currentTimeMillis());
				
				//搜藏
				CollectionItem.addCollection(gameItem);
				
				MyLog.d(TAG, "current time 444 : " + System.currentTimeMillis());
				
			}else{
				
				if(CollectionItem.isDownloadingOred(clcItem)){
					
					MyToast.showMessage(context, R.string.download_not_cancel);
					
				}else{
					String message = context.getString(R.string.collection_delete);
					DialogUtils.showConfirmDialogConfirmCancel(context, null,
							message, new OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									
									MyLog.d(TAG, "current time 111 : " + System.currentTimeMillis());
									
									detail_colletion_iv.setImageResource(R.drawable.collect_add_selector);
									
									MyLog.d(TAG, "current time 222 : " + System.currentTimeMillis());
									
									dialog.dismiss();
									
									MyLog.d(TAG, "current time 333 : " + System.currentTimeMillis());
									
									CollectionItem.cancelCollection(gameItem,false);
									
									MyLog.d(TAG, "current time 444 : " + System.currentTimeMillis());
									
								}
							}, new OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});	
					
				}
			}
		}
	
		break;

//		case R.id.detail_vr_play:
//		case R.id.detail_play:
		case R.id.detail_download_or_play_relative:
			readyToDownloadGame();
//			if (v.getId() == R.id.detail_vr_play) {
//				// 开始VR游戏
//				gameStart(Constant.GAME_MODE_VR);
//				MyLog.d(TAG, "detail_vr_play");
//			} else if (v.getId() == R.id.detail_play) {
//				// 开始普通游戏
//				gameStart(Constant.GAME_MODE_2D);
//				MyLog.d(TAG, "detail_play");
//			}
			break;
		case R.id.guide_download_relative:
			((ViewGroup)download_guide.getParent()).removeView(download_guide);
			addFavorateView();
			break;
		case R.id.guide_favorate_iv:
			((ViewGroup)favorate_guide.getParent()).removeView(favorate_guide);
			setClickble(true);
			break;
		}
	}
	

	private void readyToDownloadGame() {
		MyLog.d(TAG, "readyToDownloadGame");
		//本地测试,游戏资源放在/sdcard/jwaoo目录下.
		if(Constant.nativeBundleSwitch){
			ArrayList<GameItem> gameList = new ArrayList<GameItem>();
			gameList.add(gameItem);
			//MyPageJump.pageJumpAddGameList(context, VideoPlayActivity.class, gameList);
			jumpDialog(gameList);
			return;
		}
		
		CollectionItem clcItem = CollectionItem.query(gameItem.getId());
		int needToLoadingIcon = downloadStateIcon(clcItem);
		if(needToLoadingIcon == DOWNLOAD_STATE_TO_START){
			final int netWorkState = NetworkUtils.getNetConnectState(context);
			if (netWorkState == NetworkUtils.STATE_CONNECT_WIFI) {
				toDownloadGame();
			} else {
				String message = null;
				if (netWorkState == NetworkUtils.STATE_CONNECT_MOBILE) {
					message = context.getString(R.string.wifi_not_download_tip);
				} else if (netWorkState == NetworkUtils.STATE_CONNECT_NONE) {
					message = context.getString(R.string.wifi_and_mobie_not_download_tip);
				}
				
				DialogUtils.showConfirmDialogConfirmCancel(context, null, message,
						new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if (netWorkState == NetworkUtils.STATE_CONNECT_MOBILE) {
									toDownloadGame();
								}
								dialog.dismiss();
							}
						}, new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
			}
			
		}else if(needToLoadingIcon == DOWNLOAD_STATE_TO_END){
			boolean isShowingVideo = svrVideoView.isShowingVideo();
			if (isShowingVideo){
				svrVideoView.stopVideo();
				notPlayingUI();
			}
//			//TODO 跳转游戏
//			boolean isVrOnly = GameItem.isVROnly(gameItem);
//			boolean is2DOnly = GameItem.is2DOnly(gameItem);
//			if(isVrOnly){
//				//TODO 直接跳转VR播放
//				gameStart(Constant.GAME_MODE_VR);
//			}else if(is2DOnly){
//				gameStart(Constant.GAME_MODE_2D);
//			}else{
				//TODO 跳转到VideoPlayActivity
				ArrayList<GameItem> gameList = new ArrayList<GameItem>();
				gameList.add(gameItem);
				jumpDialog(gameList);
//			}
			
		}else{
			MyToast.showMessage(context, R.string.isDownloading);
		}
	}

	private void jumpDialog(ArrayList<GameItem> gameList) {
		if(isDismissed){
		VideoPlayDialog videoPlayDialog = new VideoPlayDialog(context,gameList);
		videoPlayDialog.show();
		videoPlayDialog.setOnDismissListener(dismissListener);
		MyDialogUtil.setDialogFullScreen(context, videoPlayDialog);
		isDismissed = false;
		}
	}
	
	private boolean isDismissed = true;
	private OnDismissListener dismissListener = new OnDismissListener(){

		@Override
		public void onDismiss(DialogInterface dialog) {
			MyLog.d(TAG, "onDismiss...");
			isDismissed = true;
		}
	};

	private void toDownloadGame() {
		MyToast.showMessage(context, context.getString(R.string.toDownoad));
		CollectionItem.addCollection(gameItem);
		detail_colletion_iv.setImageResource(R.drawable.collected_selector);
		downloadingPlayUI();
		gameDownload(gameItem);
	}

	

	private void toPlayVideo() {
		// Wifi Mobile 网络提醒
		final int netWorkState = NetworkUtils.getNetConnectState(context);
		if (netWorkState == NetworkUtils.STATE_CONNECT_WIFI) {
			toPlayVideoNow();
		} else {
			String message = null;
			if (netWorkState == NetworkUtils.STATE_CONNECT_MOBILE) {
				message = context.getString(R.string.wifi_not_play_tip);
			} else if (netWorkState == NetworkUtils.STATE_CONNECT_NONE) {
				message = context.getString(R.string.wifi_and_mobie_not_play_tip);
			}
			DialogUtils.showConfirmDialogConfirmCancel(context, null, message,
					new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (netWorkState == NetworkUtils.STATE_CONNECT_MOBILE) {
								toPlayVideoNow();

							}
							dialog.dismiss();
						}
					}, new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
		}
	}

	private void toPlayVideoNow() {
		if (svrVideoView.isShowingVideo()) {
			if (svrVideoView.isPlayingVideo()) {
				svrVideoView.PauseVideo();
			} else {
				svrVideoView.ResumeVideo();
			}
			
		} else {
			svrVideoView.startVideo();
		}
		playingUI();
	}
	
	private void pauseVideo(){
		
		if (svrVideoView.isShowingVideo()) {
			if (svrVideoView.isPlayingVideo()) {
				svrVideoView.PauseVideo();
			}
		} 
		
		playingUI();
		
	}
	
	private void resumeVideo() {

		if (svrVideoView.isShowingVideo()) {
			if (!svrVideoView.isPlayingVideo()) {
				svrVideoView.ResumeVideo();
			}
		}
		
		playingUI();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		MyLog.d(TAG, "onBackPressed...");
		if (isShowing()) {
			dismiss();
		}
	}
	
	
	public void onPause(){
		
		pauseVideo();
		
	}
	
	
	public void onResume(){
		
		resumeVideo();
		
	}


	/**
	 * 上传关注
	 *
	 */
	private void uploadFollow() {
		dataCenter.FollowActorAdd(actorItem.getId());
	}

	/**
	 * 取消关注
	 */
	private void cancelFollow() {
		dataCenter.FollowActorDel(actorItem.getId());
	}

	/**
	 * 上传赞或者踩
	 *
	 */
	private void uploadCommend() {
		dataCenter.setGameCommend(gameItem.getId());
	}
	
	
   

}
